package cn.edu.xjtu.nbrash.xbarsuite.floatbutton;

import java.util.HashMap;
import java.util.Map;

import android.content.Context;
import android.graphics.Point;
import android.view.Display;
import android.view.WindowManager;

public class FloatButtonCreator {

	@SuppressWarnings("unused")
	private static String TAG = FloatButtonCreator.class.getName();

	private static final Map<String, FloatButton> floatButtonMap = new HashMap<String, FloatButton>();

	public static FloatButton addFloatButton(String flag,
			FloatButton floatButton) {
		if (flag != null && floatButton != null) {
			if (!floatButtonMap.containsKey(flag)
					&& !floatButtonMap.containsValue(floatButton)) {
				return floatButtonMap.put(flag, floatButton);
			}
		}
		return null;
	}

	public static FloatButton getFloatButton(String flag) {
		if (flag != null) {
			return floatButtonMap.get(flag);
		}
		return null;
	}

	public static FloatButton removeFloatButton(String flag) {
		if (flag != null) {
			FloatButton floatButton = floatButtonMap.remove(flag);
			floatButton.remove();
			return floatButton;
		}
		return null;
	}

	public static FloatButton createFloatButtonByResource(String flag,
			Context context, int resid, int width, int height, int positionX,
			int positionY, float alpha) {
		if (!floatButtonMap.containsKey(flag)) {
			FloatButton floatButton = null;
			WindowManager windowManager = (WindowManager) context
					.getApplicationContext().getSystemService(
							Context.WINDOW_SERVICE);
			Display display = windowManager.getDefaultDisplay();
			Point displaySize = new Point();
			display.getSize(displaySize);
			int maxWidth = (int) (displaySize.x * FloatButton.DEFAULT_WIDTH_PERCENT);
			int maxHeight = (int) (displaySize.y * FloatButton.DEFAULT_HEIGHT_PERCENT);
			// 取较小的一边作为标准,保持参数比例
			if (maxWidth < maxHeight) {
				maxHeight = (int) (((double) maxWidth) * height / width);
			} else {
				maxWidth = (int) (((double) maxHeight) * width / height);
			}
			floatButton = new FloatButton(context, maxWidth, maxHeight);
			floatButton.setBackgroundResource(resid);
			floatButton.getLayoutParams().x = positionX;
			floatButton.getLayoutParams().y = positionY;
			floatButton.getLayoutParams().alpha = alpha;
			floatButton.add();
			addFloatButton(flag, floatButton);
			return floatButton;
		} else {
			return floatButtonMap.get(flag);
		}
	}

	public static boolean containsFloatButton(String flag) {
		return floatButtonMap.containsKey(flag);
	}
}